<!--
 * @Description: 
 * @Author: chenju
 * @Date: 2022-03-22 17:08:41
 * @LastEditors: qingyang
 * @LastEditTime: 2023-06-13 14:29:34
-->
<template>
  <CDialog
    :title="title"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
  >
    <el-form ref="formRef" :model="taskForm" :rules="obj.rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="因子名称" prop="factorName">
            <el-input v-model="taskForm.factorName" placeholder="请输入"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="英文名称" prop="enName">
            <el-input v-model="taskForm.enName" placeholder="请输入"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类别" prop="category">
            <el-select v-model="taskForm.category" style="width: 100%">
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="(item, index) in FactorCategoryOptions"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="国别" prop="country">
            <el-select v-model="taskForm.country" style="width: 100%">
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="(item, index) in countryOptions"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排放因子" prop="emissionFactor">
            <el-input
              v-model="taskForm.emissionFactor"
              placeholder="请输入"
              v-decimal-only:6
              type="number"
              @wheel.stop.prevent
            >
              <template #append>
                <el-form-item prop="factorUnit" class="unit-form">
                  <el-select v-model="taskForm.factorUnit" style="width: 130px; margin-left: 0px">
                    <el-option
                      :label="item.dataValue"
                      :value="item.dataValue"
                      v-for="item in UnitAllOption"
                      :key="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="基准年" prop="baseYear">
            <el-date-picker
              style="width: 100%"
              v-model="taskForm.baseYear"
              value-format="YYYY"
              type="year"
              placeholder="请选择年份"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="核算边界：" prop="boundary">
            <el-select v-model="taskForm.boundary" style="width: 100%">
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="(item, index) in accountBoundaryOptions"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="因子来源" prop="factorSource">
            <el-select v-model="taskForm.factorSource" style="width: 100%">
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="(item, index) in FactorSourceOptions"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="标签" prop="comment" class="tag-form">
            <div>
              <el-input
                class="tag-wrap"
                ref="InputRef"
                v-model="inputValue"
                @blur="handleInputConfirm"
                @keyup.enter="handleInputConfirm"
                maxlength="6"
                placeholder="请输入"
              >
                <template #prefix>
                  <div>
                    <el-tag
                      type="info"
                      closable
                      @close="handleClose(item)"
                      v-for="(item, index) in taskForm.tags"
                      :key="index"
                      >{{ item }}</el-tag
                    >
                  </div>
                </template>
              </el-input>
              <p class="g-font-12n3 g-mt4">
                可创建标签便于分类检索，每个模型支持创建最多 5 个标签，每个标签可输入 6 个字
              </p>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="comment">
            <el-input
              type="textarea"
              v-model="taskForm.comment"
              placeholder="请输入"
              show-word-limit
              maxlength="255"
              rows="2"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件" prop="fileList">
            <g-upload
              inline
              :span="24"
              :file-size-limit="10"
              :action="uploadFilePostUrlV3"
              :postParams="{
                groupType: 'PCF_FACTOR',
                scope: AllBizScopeEnum.PCF,
                needRename: false
              }"
              v-model:fileList="taskForm.fileList"
              @change="onChange"
              accept=".pdf, .docx, .xlsx, .jpg, .jpeg, .png"
            >
              <template #default="{ loading: btnLoading }">
                <el-button :loading="btnLoading"
                  ><CIcon type="c-xian-shangchuan" class="g-mr4"></CIcon>上传文件</el-button
                >
              </template>
            </g-upload>
            <p class="g-font-12n3 g-mt4"
              >*支持.pdf, .docx, .xlsx, .jpg, .jpeg,
              .png格式文件上传，用于上传报告、文献、现场测量数据等证明材料。最大不超过10M</p
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'AddFactor'
};
</script>
<script lang="ts" setup>
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { useMessage } from '@/hooks/useMessage';
import * as obj from './rules';
import { uploadFilePostUrlV3 } from '@/apis/common/common';
import { addFactor, editFactorDetail } from '@/apis/pcf/database/factorList';
import { IFactorDetail, IFactorAdd } from '@/apis/pcf/database//model/factorListModel';
import { getBase } from '@/apis/common/common';
import { GUpload } from '@/components/GUpload/index';
import { useTag } from '@/views/pcf/myModel/addModel/useTag';
import { AllBizScopeEnum } from '@/commonModule/constants';

import { FactorCategoryOptions, FactorSourceOptions, countryOptions } from '@/constants/enum';
interface SelectFillTypeDialogProps {
  visible: boolean;
  info: IFactorDetail | null;
}
const props = withDefaults(defineProps<SelectFillTypeDialogProps>(), {});
const emit = defineEmits(['update:visible', 'refresh']);

const UnitAllOption = ref([] as any[]);
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
const title = computed(() => {
  return props.info ? '编辑因子' : '新增因子';
});
watch(
  () => dialogVisible.value,
  visible => {
    if (visible) {
      init();
    } else {
      formRef.value?.resetFields();
    }
  }
);

const formRef = ref();
const loading = ref(false);
const { createMessage } = useMessage();
const taskForm = reactive({
  fileList: [] as any[],
  factorName: '',
  enName: '',
  category: '',
  country: '',
  factorUnit: '',
  emissionFactor: '',
  baseYear: '',
  factorSource: '',
  version: '',
  comment: '',
  tags: [] as string[]
});
const { handleInputConfirm, handleClose, InputRef, inputValue } = useTag(taskForm);

getBase('footprint:FACTOR_UNIT').then(res => {
  UnitAllOption.value = res ?? [];
});

const onChange = (file: any, fileList: any) => {
  formRef.value?.clearValidate('fileList');
  formRef.value?.scrollToField('fileList');
};
function handleConfirm() {
  formRef.value?.validate(async (valid: boolean, val: any) => {
    if (valid) {
      loading.value = true;
      const file = taskForm.fileList[0];
      const { url, name } = file;
      let params: IFactorAdd = {
        attachment: url,
        attachmentName: name,
        factorName: taskForm.factorName,
        enName: taskForm.enName,
        category: taskForm.category,
        country: taskForm.country,
        factorUnit: taskForm.factorUnit,
        emissionFactor: taskForm.emissionFactor,
        factorSource: taskForm.factorSource,
        baseYear: taskForm.baseYear,
        comment: taskForm.comment,
        tag: taskForm.tags.join(',')
      };
      try {
        if (props.info) {
          params.factorNo = props.info.factorNo;
          await editFactorDetail(params);
          createMessage.success('编辑因子成功');
        } else {
          await addFactor(params);
          createMessage.success('新增因子成功');
        }
        dialogVisible.value = false;
        init();
        emit('refresh');
      } finally {
        loading.value = false;
      }
    } else {
      // 滚动到验证不通过的item上
      let keys = Object.keys(val);
      formRef.value?.scrollToField(keys[0]);
    }
  });
}
async function init() {
  if (props.info) {
    let { info } = props;
    taskForm.factorName = info.factorName;
    taskForm.enName = info.enName;
    taskForm.category = info.category;
    taskForm.country = info.country;
    taskForm.factorUnit = info.factorUnit;
    taskForm.emissionFactor = info.emissionFactor;
    taskForm.baseYear = info.baseYear;
    taskForm.comment = info.comment;
    taskForm.factorSource = info.factorSource;
    taskForm.factorName = info.factorName;
    taskForm.tags = info.tag ? info.tag.split(',') : [];

    if (info.attachment) {
      taskForm.fileList = [{ name: info.attachmentName, url: info.attachment }];
    } else {
      taskForm.fileList = [];
    }
  } else {
    taskForm.factorName = '';
    taskForm.enName = '';
    taskForm.category = '';
    taskForm.country = '';
    taskForm.factorUnit = '';
    taskForm.emissionFactor = '';
    taskForm.baseYear = '';
    taskForm.comment = '';
    taskForm.factorName = '';
    taskForm.fileList = [];
    taskForm.tags = [];
    taskForm.factorSource = '';
    formRef.value?.resetFields();
  }
}
</script>
<style lang="scss" scoped>
:deep(.el-input-group__append) {
  padding: 0;
}
.unit-form {
  width: 100%;
  :deep(.select-trigger) {
    width: 111px;
    .el-input__wrapper {
      width: 100%;
    }
  }
}
.tag-wrap {
  width: 632px;
}
</style>
